﻿using System.Diagnostics;
using System.Windows.Media;

namespace ScrollerMusicPlayerUI.Controls.Primitives
{
    public class ScrollerManager
    {
        private BetterWarpPanel _panel;
        private DateTime _startTime;
        private TimeSpan _interval;
        private bool _isRunning;
        private double _lastTimeValue;
        private FillManager _fillManager;
        public ScrollerManager(BetterWarpPanel panel, FillManager fillManager)
        {
            _panel = panel;
            _interval = TimeSpan.FromSeconds(1);
            _fillManager = fillManager;
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }

        private void CompositionTarget_Rendering(object? sender, EventArgs e)
        {
            if (_isRunning == false) return;
            var delta = DateTime.Now - _startTime;

            var timeValue = delta.TotalSeconds % _interval.TotalSeconds;
            var ratio = timeValue / _interval.TotalSeconds;
            var unitSize = _panel.ActualWidth / _panel.Columns;
            var offset = -unitSize * ratio;
            _panel.Offset = offset;
            if (_lastTimeValue > timeValue)
            {
                RemoveRange();
                AppendRange();

            }
           
            _lastTimeValue = timeValue;
        }

        private void RemoveRange()
        {
            if (_panel.Children.Count >= _panel.Columns)
                _panel.Children.RemoveRange(0, _panel.Columns);
        }

        private void AppendRange()
        {
            for (int i = 0; i < _panel.Columns; i++)
            {
                _fillManager.ContinueFill();
            }
        }


        public void Start()
        {
            if (_isRunning == true) return;
            _isRunning = true;
            _startTime = DateTime.Now;
            _lastTimeValue = 0d;

            AppendRange();
        }


    }
}
